#!/usr/bin/env python3
"""
Git 子模块管理核心功能
"""

import subprocess
import json
import logging
from pathlib import Path
from typing import Dict, List, Optional, Tuple

logger = logging.getLogger(__name__)

class GitCommandError(Exception):
    """Git 命令执行错误"""
    pass

class GitSubmoduleManager:
    """Git 子模块管理器"""
    
    def __init__(self, repo_path: str = "."):
        self.repo_path = Path(repo_path).absolute()
        self._validate_git_repo()
    
    def _run_git_command(self, args: List[str], check: bool = True) -> Tuple[bool, str]:
        """执行 git 命令"""
        try:
            cmd = ["git", "-C", str(self.repo_path)] + args
            logger.debug(f"执行命令: {' '.join(cmd)}")
            
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                check=check,
                timeout=30  # 30秒超时
            )
            return True, result.stdout.strip()
        except subprocess.CalledProcessError as e:
            error_msg = f"Git 命令失败: {e.stderr.strip()}"
            logger.error(error_msg)
            return False, error_msg
        except subprocess.TimeoutExpired:
            error_msg = "Git 命令执行超时"
            logger.error(error_msg)
            return False, error_msg
    
    def _validate_git_repo(self) -> None:
        """验证当前目录是 Git 仓库"""
        success, _ = self._run_git_command(["rev-parse", "--git-dir"])
        if not success:
            raise GitCommandError(f"不是 Git 仓库: {self.repo_path}")
    
    def check_mirror_availability(self, mirror_url: str) -> bool:
        """检查镜像可用性"""
        logger.info(f"检查镜像可用性: {mirror_url}")
        success, _ = self._run_git_command(["ls-remote", mirror_url], check=False)
        return success
    
    def get_repo_info(self, repo_url: str) -> Dict:
        """获取仓库信息（标签、分支等）"""
        info = {"tags": 0, "branches": 0, "last_commit": None}
        
        # 获取标签数量
        success, output = self._run_git_command(["ls-remote", "--tags", repo_url], check=False)
        if success:
            info["tags"] = len([line for line in output.split('\n') if line])
        
        # 获取分支数量
        success, output = self._run_git_command(["ls-remote", "--heads", repo_url], check=False)
        if success:
            info["branches"] = len([line for line in output.split('\n') if line])
        
        # 获取最后提交时间
        success, output = self._run_git_command(["ls-remote", "--sort=-committerdate", repo_url, "HEAD"], check=False)
        if success and output:
            info["last_commit"] = output.split()[0]
        
        return info
    
    def setup_insteadof_rule(self, original_url: str, mirror_url: str) -> bool:
        """配置 insteadOf 规则"""
        config_name = f"url.{mirror_url}.insteadOf"
        success, _ = self._run_git_command(["config", "--local", config_name, original_url])
        
        if success:
            logger.info(f"配置成功: {original_url} → {mirror_url}")
        else:
            logger.error(f"配置失败: {original_url} → {mirror_url}")
        
        return success
    
    def init_submodules(self) -> bool:
        """初始化子模块"""
        logger.info("初始化子模块...")
        success, output = self._run_git_command(["submodule", "update", "--init", "--recursive"])
        
        if success:
            logger.info("子模块初始化完成")
        else:
            logger.error(f"子模块初始化失败: {output}")
        
        return success
    
    def get_submodules(self) -> List[Dict]:
        """获取所有子模块信息"""
        success, output = self._run_git_command(["submodule", "status"])
        if not success:
            return []
        
        submodules = []
        for line in output.split('\n'):
            if line.strip():
                parts = line.split()
                if len(parts) >= 2:
                    submodules.append({
                        "commit": parts[0].lstrip('+-'),
                        "path": parts[1],
                        "branch": parts[2] if len(parts) > 2 else None
                    })
        
        return submodules

